/**
 * Copyright (c) 2018-2028, Chill Zhuang 庄骞 (smallchill@163.com).
 * <p>
 * Licensed under the GNU LESSER GENERAL PUBLIC LICENSE 3.0;
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 * <p>
 * http://www.gnu.org/licenses/lgpl.html
 * <p>
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
package org.springblade.modules.bank.controller;

import cn.hutool.core.util.RandomUtil;
import com.alibaba.excel.util.FileUtils;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import io.swagger.annotations.ApiParam;
import com.github.xiaoymin.knife4j.annotations.ApiOperationSupport;
import lombok.AllArgsConstructor;

import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.validation.Valid;

import org.apache.commons.codec.Charsets;
import org.springblade.core.mp.support.Condition;
import org.springblade.core.mp.support.Query;
import org.springblade.core.tool.api.R;
import org.springblade.core.tool.utils.Func;
import org.springblade.modules.bank.util.DownloadUploadUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.FileCopyUtils;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.bind.annotation.RequestParam;
import com.baomidou.mybatisplus.core.metadata.IPage;
import org.springblade.modules.bank.entity.TmVistFile;
import org.springblade.modules.bank.vo.TmVistFileVO;
import org.springblade.modules.bank.service.ITmVistFileService;
import org.springblade.core.boot.ctrl.BladeController;
import org.springframework.web.multipart.MultipartFile;
import springfox.documentation.annotations.ApiIgnore;

import java.io.*;
import java.net.URLEncoder;
import java.time.LocalDate;
import java.time.format.DateTimeFormatter;
import java.util.*;

/**
 *  控制器
 *
 * @author Blade
 * @since 2023-09-24
 */
@RestController
@RequestMapping("/tmvistfile")
@Api(value = "", tags = "接口")
public class TmVistFileController extends BladeController {

	@Autowired
	private ITmVistFileService tmVistFileService;

	@Value("${recordFilePath}")
	private String recordFilePath;

	@Value("${filePath}")
	private String filePath;
	/**
	 * 详情
	 */
	@GetMapping("/detail")
	@ApiOperationSupport(order = 1)
	@ApiOperation(value = "详情", notes = "传入tmVistFile")
	public R<TmVistFile> detail(TmVistFile tmVistFile) {
		TmVistFile detail = tmVistFileService.getOne(Condition.getQueryWrapper(tmVistFile));
		return R.data(detail);
	}

	/**
	 * 分页 
	 */
	@GetMapping("/list")
	@ApiOperationSupport(order = 2)
	@ApiOperation(value = "分页", notes = "传入tmVistFile")
	public R<IPage<TmVistFile>> list(TmVistFile tmVistFile, Query query) {
		IPage<TmVistFile> pages = tmVistFileService.page(Condition.getPage(query), Condition.getQueryWrapper(tmVistFile));
		return R.data(pages);
	}

	/**
	 * 自定义分页 
	 */
	@GetMapping("/page")
	@ApiOperationSupport(order = 3)
	@ApiOperation(value = "分页", notes = "传入tmVistFile")
	public R<IPage<TmVistFileVO>> page(TmVistFileVO tmVistFile, Query query) {
		IPage<TmVistFileVO> pages = tmVistFileService.selectTmVistFilePage(Condition.getPage(query), tmVistFile);
		return R.data(pages);
	}

	/**
	 * 新增 
	 */
	@PostMapping("/save")
	@ApiOperationSupport(order = 4)
	@ApiOperation(value = "新增", notes = "传入tmVistFile")
	public R save(@Valid @RequestBody TmVistFile tmVistFile) {
		return R.status(tmVistFileService.save(tmVistFile));
	}

	/**
	 * 修改 
	 */
	@PostMapping("/update")
	@ApiOperationSupport(order = 5)
	@ApiOperation(value = "修改", notes = "传入tmVistFile")
	public R update(@Valid @RequestBody TmVistFile tmVistFile) {
		return R.status(tmVistFileService.updateById(tmVistFile));
	}

	/**
	 * 新增或修改 
	 */
	@PostMapping("/submit")
	@ApiOperationSupport(order = 6)
	@ApiOperation(value = "新增或修改", notes = "传入tmVistFile")
	public R submit(@Valid @RequestBody TmVistFile tmVistFile) {
		return R.status(tmVistFileService.saveOrUpdate(tmVistFile));
	}

	
	/**
	 * 删除 
	 */
	@PostMapping("/remove")
	@ApiOperationSupport(order = 7)
	@ApiOperation(value = "逻辑删除", notes = "传入ids")
	public R remove(@ApiParam(value = "主键集合", required = true) @RequestParam String ids) {
		return R.status(tmVistFileService.removeByIds(Func.toLongList(ids)));
	}

	@PostMapping("/uploadFile")
	@ApiOperationSupport(order = 3)
	@ApiOperation(value = "上传证据复制提取单[案件文书][简易]", notes = "传入上传附件/需删除附件/参数")
	@Transactional
	public R uploadFile(
			@RequestParam(value = "file", required = false) MultipartFile[] file,
			@RequestParam("deleteIds") String deleteIds,
			@RequestParam("sourceId") String sourceId, HttpServletRequest req){
		if (deleteIds!=null&&!"".equals(deleteIds)){
			tmVistFileService.removeByIds(Func.toLongList(deleteIds));
//			File file = new File(fileName);
//			if(file.exists()){
//				file.delete();
//			}
		}
		if (file!=null&&file.length>0){
			for (MultipartFile temp:file){
				uploadFile(temp,sourceId);
			}
		}
		return R.success("上传成功");
	}

	private void uploadFile(MultipartFile file,String sourceId){
		/*
		 * 这段代码执行完毕之后，图片上传到了工程的跟路径； 大家自己扩散下思维，如果我们想把图片上传到
		 * d:/files大家是否能实现呢？ 等等;
		 * 这里只是简单一个例子,请自行参考，融入到实际中可能需要大家自己做一些思考，比如： 1、文件路径； 2、文件名；
		 * 3、文件格式; 4、文件大小的限制;
		 */

		BufferedOutputStream out = null;
		try {
			DateTimeFormatter dtf = DateTimeFormatter.ofPattern("yyyy-MM-dd");
			String today = LocalDate.now().format(dtf);
			String path = recordFilePath + "/img/" + today;
			File pathTemp = new File(path);
			if(!pathTemp.exists()){
				pathTemp.mkdirs();
			}

			String fileOriType = file.getOriginalFilename().substring(file.getOriginalFilename().lastIndexOf('.')+1).toLowerCase();
			String fileName = RandomUtil.randomNumbers(12)+"."+fileOriType;
			String filePath = path + "/" + fileName;
			out = new BufferedOutputStream(new FileOutputStream(new File(filePath)));
			out.write(file.getBytes());
			out.flush();
			out.close();

			TmVistFile tmVistFile = new TmVistFile();
			tmVistFile.setSourceId(Long.parseLong(sourceId));
			tmVistFile.setFileName(fileName);
			tmVistFile.setFilePath(filePath);
			tmVistFile.setFileSize(file.getSize());
			tmVistFile.setFileType(fileOriType);
			tmVistFileService.save(tmVistFile);
		} catch (Exception e) {
			e.printStackTrace();
		}
	}

	@PostMapping("/updateFile")
	@ApiOperationSupport(order = 3)
	@ApiOperation(value = "上传证据复制提取单[案件文书][简易]", notes = "传入上传附件/需删除附件/参数")
	@Transactional
	public R updateFile(
			@RequestParam(value = "file", required = false) MultipartFile[] files,
			@RequestParam(value = "id", required = false) String id){
		/*
		 * 这段代码执行完毕之后，图片上传到了工程的跟路径； 大家自己扩散下思维，如果我们想把图片上传到
		 * d:/files大家是否能实现呢？ 等等;
		 * 这里只是简单一个例子,请自行参考，融入到实际中可能需要大家自己做一些思考，比如： 1、文件路径； 2、文件名；
		 * 3、文件格式; 4、文件大小的限制;
		 */

		if (files.length==0){
			return R.fail("附件为空，操作失败");
		}
		MultipartFile file = files[0];
		BufferedOutputStream out = null;
		try {
			DateTimeFormatter dtf = DateTimeFormatter.ofPattern("yyyy-MM-dd");
			String today = LocalDate.now().format(dtf);
			String path = filePath + "/file/" + today;
			File pathTemp = new File(path);
			if(!pathTemp.exists()){
				pathTemp.mkdirs();
			}

			String fileOriType = file.getOriginalFilename().substring(file.getOriginalFilename().lastIndexOf('.')+1).toLowerCase();
			String fileName = RandomUtil.randomNumbers(12)+"."+fileOriType;
			String filePath = path + "/" + fileName;
			out = new BufferedOutputStream(new FileOutputStream(new File(filePath)));
			out.write(file.getBytes());
			out.flush();
			out.close();

			TmVistFile tmVistFile = tmVistFileService.getById(id);
//			tmVistFile.setFileName(fileName);
			tmVistFile.setFilePath(filePath);
			tmVistFile.setFileSize(file.getSize());
			tmVistFile.setFileType(fileOriType);
			tmVistFileService.updateById(tmVistFile);
		} catch (Exception e) {
			e.printStackTrace();
		}
		return R.success("上传成功");
	}

	@RequestMapping("/getImg")
	@ApiOperationSupport(order = 4)
	@ApiOperation(value = "获取证据复制提取单附件[案件文书][简易]", notes = "无参数")
	public void getImg(TmVistFile tmVistFile, HttpServletRequest request, HttpServletResponse response) throws Exception {
		Map<String,String> map = new HashMap<>();
		map.put("filePath",tmVistFile.getFilePath());
		map.put("fileName",tmVistFile.getFileName());
		DownloadUploadUtil.Download(map,request,response);
	}

	@RequestMapping("/downloadFile")
	@ApiOperationSupport(order = 4)
	public void downloadFile(TmVistFile tmVistFile, HttpServletResponse response) throws IOException {
//		response.setContentType("application/octet-stream");
		response.setCharacterEncoding(Charsets.UTF_8.name());
		DateTimeFormatter dtf = DateTimeFormatter.ofPattern("yyyy-MM-dd");
		String today = LocalDate.now().format(dtf);
		TmVistFile oriTmVistFile = tmVistFileService.getById(tmVistFile.getId());
		response.setHeader("Content-disposition", "attachment;filename=" + URLEncoder.encode(oriTmVistFile.getFileName()+today+"."+oriTmVistFile.getFileType(),"UTF-8"));
		byte[] fileToByteArray = FileUtils.readFileToByteArray(new File(oriTmVistFile.getFilePath()));
		response.getOutputStream().write(fileToByteArray);

		//获取输出流对象（用于写文件）
//		ServletOutputStream os = response.getOutputStream();
//		//下载文件,使用spring框架中的FileCopyUtils工具
//
//		FileCopyUtils.copy(FileCopyUtils.copyToByteArray(new File(oriTmVistFile.getFilePath())),os);
	}
}
